package com.cn.sys.main.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cn.sys.common.Constants;
import com.cn.sys.frame.util.JsonUtil;
import com.cn.sys.frame.web.BaseController;
import com.cn.sys.main.entity.SysFunction;
import com.cn.sys.main.entity.SysModule;
import com.cn.sys.main.entity.SysUser;
import com.cn.sys.main.service.SysFunctionService;
import com.cn.sys.main.service.SysModuleService;
import com.cn.sys.main.service.SysUserService;
import com.cn.sys.main.util.AppUtil;

@Controller
public class SysLoginController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(SysLoginController.class);
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysModuleService sysModuleService;
	@Autowired
	private SysFunctionService sysFunctionService;
	
	@RequestMapping(value = "/toLogin", method = RequestMethod.GET)
	public String toLogin(HttpSession session){
		session.invalidate();
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpSession session){
		session.invalidate();
		return "login";
	}
	
	@RequestMapping(value = "/toHome", method = RequestMethod.GET)
	public String toHome(){
		
		return "home";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, String userName, String passWord) throws Exception{
		ModelAndView mav = new ModelAndView();
		if(StringUtils.isNotBlank(userName)&&StringUtils.isNotBlank(passWord)){
			SysUser user = sysUserService.getByUserName(userName);
			passWord = DigestUtils.md5DigestAsHex(passWord.getBytes()).toUpperCase();
			if(user!=null){
				if(StringUtils.equals(passWord, user.getPassWord())&&StringUtils.equals("1", user.getStatus())){
					String modulesJson = "";
					List<SysModule> list = null;
					List<SysFunction> list2 = null;
					if("system".equals(userName)){
						list = sysModuleService.getAvailableModules();
						list2 = sysFunctionService.getFunctionsByUserId(null);
					}else {
						list = sysModuleService.getAvailableModulesByUserId(user.getId());
						list2 = sysFunctionService.getFunctionsByUserId(user.getId());
					}
					
					modulesJson = this.getModulesJson(list);
					mav.addObject("userModules", modulesJson);
					mav.addObject("loginUser", user.getName()+" ["+userName+"]");
					mav.addObject("userId", user.getId());
					user.setLoginIp(AppUtil.getIpAddr(request));
					user.setLoginTime(new Date());
					
					this.setSessionUser(request, user);
					this.setSessionModuleAndFunc(request, list, list2);
					
					sysUserService.userLogin(user);
					logger.info("用户  [" + userName + "] 登录成功!!!");
					mav.setViewName("main");
				}else if(!StringUtils.equals(passWord, user.getPassWord())) {
					mav.addObject("errorMsg", "对不起,密码错误!");
					mav.setViewName("login");
				}else if(!StringUtils.equals("1", user.getStatus())){
					mav.addObject("errorMsg", "对不起,帐号已被禁用!");
					mav.setViewName("login");
				}else {
					mav.addObject("errorMsg", "对不起,用户名密码错误!");
					mav.setViewName("login");
				}
			}else {
				mav.addObject("errorMsg", "对不起,不存在["+userName+"]用户!");
				mav.setViewName("login");
			}
			return mav;
		}else {
			mav.addObject("errorMsg", "对不起,请输入用户名密码!");
			mav.setViewName("login");
			return mav;
		}
		
	}
	
	 @RequestMapping("/doLogout")  
	 public String logout(HttpSession session) throws Exception {
		 SysUser user = (SysUser) session.getAttribute(Constants.USER_CONTEXT);
		 if(user!=null){
			 user.setLogoutTime(new Date());
			 sysUserService.userLogout(user);
		 }
		 session.removeAttribute(Constants.USER_CONTEXT);
		 session.invalidate();
		 logger.info("安全退出!!!");
	     return "forward:/index.jsp";  
	 }
	 
	 private String getModulesJson(List<SysModule> list){
			StringBuffer moduleBuffer = new StringBuffer();
			
			for (SysModule sysModule : list) {
				if(sysModule.getParentId()==null){
					moduleBuffer.append("{\"menuid\":\"").append(sysModule.getId())
					.append("\",\"menuname\":").append(JsonUtil.toJson(sysModule.getModuleName()))
					.append(",\"icon\":").append(JsonUtil.toJson(sysModule.getIcon())).append(",\"menus\":[");
					int len = moduleBuffer.length();
					for (SysModule childModule : list) {
						if(childModule.getParentId()!=null&&childModule.getParentId().equals(sysModule.getId())){
							moduleBuffer.append("{\"menuid\":\"").append(childModule.getId())
							.append("\",\"menuname\":").append(JsonUtil.toJson(childModule.getModuleName()))
							.append(",\"icon\":").append(JsonUtil.toJson(childModule.getIcon()))
							.append(",\"url\":").append(JsonUtil.toJson(childModule.getUrl())).append("},");
						}
					}
					if(len != moduleBuffer.length()){
						moduleBuffer.deleteCharAt(moduleBuffer.length()-1);
					}
					moduleBuffer.append("]},");
				}
			}
			if(moduleBuffer.length()>0){
				moduleBuffer.deleteCharAt(moduleBuffer.length()-1);
			}
			moduleBuffer.insert(0, "{\"menus\":[").append("]}");
			return moduleBuffer.toString();
		}
}
